package lab.galaxy.XuebaHookPlugin;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by zjzdy on 2017/5/26.
 * This class only a example for use application and build&store imei
 */

public class Hook_temp_DevicesEntity_setImei {
    public static String className = "com.template.bean.DevicesEntity";
    public static String methodName = "setImei";
    public static String methodSig = "(Ljava/lang/String;)V";
    public static Application application = null;
    public static void hook(Object thiz,String str) {
        Log.i("YAHFA", "com.template.bean.DevicesEntity setImei hooked:"+str);
        Class c = thiz.getClass();
        Method method = null;
        SharedPreferences sp = null;
        if(application != null)
        {
            sp = application.getSharedPreferences("HookInfo", Context.MODE_PRIVATE);
            str = sp.getString("imei",null);
            if(str != null) {
                Toast.makeText(application, "IMEI:"+str, Toast.LENGTH_SHORT).show();
                origin(thiz, str);
                try {
                    method = c.getMethod("setDeviceid",String.class);
                    method.invoke(thiz,"");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
        }
        String str2 = "";
        if(!str2.isEmpty())
            str = str2;
        else
            str = "861648000";
        str += String.valueOf((int)(Math.random()*10));
        str += String.valueOf((int)(Math.random()*10));
        str += String.valueOf((int)(Math.random()*10));
        str += String.valueOf((int)(Math.random()*10));
        str += String.valueOf((int)(Math.random()*10));
        str += "0";
        int sum=0;
        boolean isEven=false;
        for(int i=str.length();i>0;i--)
        {

            int k=Integer.parseInt(str.substring(i-1,i));
            if(isEven){
                k=k*2;
                if(k/10!=0)
                    k=k/10+k%10;
            }
            isEven=!isEven;
            sum+=k;
        }
        int i=0;
        if(sum%10!=0)
            i=10-sum%10;
        if(sp != null)
        {
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("imei",str+i);
            editor.commit();
            Toast.makeText(application, "IMEI:"+str, Toast.LENGTH_SHORT).show();
        }
        origin(thiz, str+i);
        try {
            method = c.getMethod("setDeviceid",String.class);
            method.invoke(thiz,"");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void origin(Object thiz, String str) {
        Log.w("YAHFA", "should not be here");
    }
}
